<template>
	<view></view>
</template>
<script>
	var heartbeat_count = 0;
	export default {
		config: {

		},
		onBackPress(options) {
			var that = this;
			// 点击虚拟键或者侧滑的时候触发（不允许返回）
			if (options.from === 'backbutton') {
				// 询问弹窗
				that.fnLeaveRoom();
				return true
			}
			// 否则则允许返回
			return false;
		},
		components: {

		},
		computed: {

		},
		watch: {

		},
		data() {
			return {
				isSuccess: false, // isSuccess 通常用于标记 WebSocket 连接是否成功。当你尝试连接 WebSocket 服务器时，一旦连接成功（即 onOpen 事件触发），你可以将 isSuccess 设置为 true。
				isClose: false, // 初始化为 false   在 beforeDestroy 生命周期钩子中，你应该将 this.isClose 设置为 true，以防止在组件销毁后继续尝试重新连接 WebSocket。
			};
		},
		onReady() {
			const that = this
			uni.createSelectorQuery().select('.top-hr').boundingClientRect(rect => {
				that.scrollHeight = uni.getSystemInfoSync().windowHeight - rect.bottom;
				that.submitPositionLeft = uni.getSystemInfoSync().windowWidth / 2 - 96 / 2;
			}).exec();
		},
		mounted() {
			const that = this
		},
		onLoad(options) {
			var that = this;

			that.init();
		},
		onShow: function() {

		},
		beforeDestroy() {
			var that = this;
			console.log('beforeDestroy')

			that.isClose = true;

			if (this.socketTask) {
				this.socketTask.close();
			}
			clearInterval(this.timer);
			that.timer = null;
		},
		methods: {
			init() {
				var that = this;
			},

			//连接websocket
			connectSocket() {
				let that = this;
				console.log('调用连接websocket')
				let token = uni.getStorageSync('TOKEN_YX');
				if (!that.user_info.id || !that.group_info.id) {
					that.fnNotify('参数异常');
					return false;
				}
				that.socketTask = uni.connectSocket({
					url: `ws://${that.$config.webSocketIp}:9999?token=${token}&user_id=${that.user_info.id}&group_id=${that.group_info.id}`,
					success(res) {
						console.log("websocket连接成功1");
					},
					fail(err) {
						console.log("报错", err);
					}
				});
				that.socketTask.onOpen(function(res) {
					console.log('WebSocket连接已打开！');
					that.isSuccess = true
					that.heart()

					//发送消息
					setTimeout(function() {
						var content = '进入房间';
						content = "#" + content + "#-" + that.user_info.id;
						that.fnSendMessage(content);
					}, 500)
				})

				that.socketTask.onMessage(function(res) {
					// console.log('收到服务器内容：' + res.data);
					that.handlerServiceMsg(JSON.parse(res.data)) //这里是对获取到的数据进行操作
				});


				that.socketTask.onError(function(res) {
					console.log('WebSocket连接打开失败，请检查！');
					that.fnNotify('WebSocket连接打开失败，请检查！');
					that.wsStatus = false;
					console.log(res);
					// that.isSuccess = false
					// that.connectSocket()

					//进入重新连接
					that.reconnect();
					// if (that.game_finished == 0) {
					// 	that.fnConfirmLeave();
					// }
				})
				// // 监听连接关闭 -
				that.socketTask.onClose((e) => {
					console.log('WebSocket连接关闭！');
					clearInterval(that.timer)
					that.timer = ''

					that.reconnect()
				})
				console.log(that.socketTask)
			},

			//进入重新连接
			reconnect() {
				var that = this;
				if (that.isClose == true) {
					return false;
				}
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}

				console.log('进入断线重连');

				// 如果 socketTask 存在并且连接是打开的，显式关闭它
				if (this.socketTask && this.socketTask.readyState === 1) { // WebSocket.OPEN
					this.socketTask.close();
				}

				this.socketTask = null;
				this.connectSocket()
			},

			//发送消息
			sendSocketMessage(msg) {
				if (this.isSuccess) {
					return new Promise((reslove, reject) => {
						this.socketTask.send({
							data: msg,
							success(res) {
								// console.log('发送成功')
								reslove(res)
							},
							fail(res) {
								console.log('发送失败')
								console.log(res)
								reject(res)
							}
						});
					})
				} else {
					// 显示错误提示
					this.fnNotify('WebSocket连接未建立，请稍后再试');
				}
			},

			//心跳
			heart() {
				let that = this;
				clearInterval(this.timer);
				this.timer = null;

				this.timer = setInterval(() => {
					console.log('心跳！！！')
					that.sendSocketMessage(JSON.stringify({
						"game": "jspc",
						"heartbeat": heartbeat_count,
						"type": "heartbeat",
						"start_time": Date.now() / 1000
					})).then(res => {
						// console.log('心跳成功')
					}).catch(res => {
						console.log('发送失败')
						console.log((res))
					})
				}, 5000)
			},
		}
	}
</script>

<style lang="less">

</style>